import { createRouter, createWebHashHistory } from 'vue-router'
// import Home from '../views/home/Home'
// import Login from '../views/login/Login'
// import Register from '../views/register/Register'
// import Shop from '../views/shop/Shop'
/*
  通过异步路由，让页面加载更快
*/
const routes = [
  {
    path: '/',
    name: 'Home',
    // 访问这个页面才回去加载这个页面的代码，首屏加载的速度更快
    component: () => import(/* webpackChunkName: "home" */'../views/home/Home')
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import(/* webpackChunkName: "shop" */'../views/shop/Shop')
  },
  {
    path: '/login',
    name: 'Login',
    // component: Login,
    component: () => import(/* webpackChunkName: "login" */'../views/login/Login'),
    // beforeEnter 路由进去之前，类似于beforeEach
    beforeEnter (to, from, next) {
      // const isLogin = localStorage.isLogin 下面这句是简写
      const { isLogin } = localStorage
      isLogin ? next({ name: 'Home' }) : next()
    }
  },
  {
    path: '/register',
    name: 'Register',
    // component: Register,
    component: () => import(/* webpackChunkName: "register" */'../views/register/Register'),
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage
      isLogin ? next({ name: 'Home' }) : next()
    }
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由跳转前，执行此方法
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.isLogin
  if (!isLogin && to.name !== 'Login' && to.name !== 'Register') {
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router
